#include "SpriteAnimator.h"

using namespace SolidityEngine;

SpriteAnimator::SpriteAnimator():
    _w(1),
    _h(1),
    _fps(16.0f),
    _framecount(_w*_h),
    _renderer(NULL),
    _looping(true),
    _playing(true),
    _currentframe(0),
    _range{0,_framecount-1}
{
    SetInterval(1000.0f/_fps);
    //ctor
}

SpriteAnimator::~SpriteAnimator()
{
    //dtor
}

void SpriteAnimator::SetSpritesheetSize(int columns, int rows)
{
    _w=columns;
    _h=rows;
    _framecount=_w*_h;

}

void SpriteAnimator::Loop(int start, int stop){
    _range[0]=start;
    _range[1]=stop;
    _currentframe=_range[0];
    _playing=true;
    _looping=true;
}

void SpriteAnimator::Play(int start, int stop){
    _range[0]=start;
    _range[1]=stop;
    _currentframe=_range[0];
    _playing=true;
    _looping=false;
}

SpriteAnimator* SpriteAnimator::_Clone()
{
    return new SpriteAnimator(*this);
}

void SpriteAnimator::_OnStart()
{
    _renderer=_gameobject->GetComponent<SpriteRenderer>();
    _time=Time::CurrentTime();
    int row=_currentframe/_w;
    int col=_currentframe%_w;
    Rect imagerect(1.0f/_w*col,1.0f/_h*row,1.0f/_w,1.0f/_h);
    _renderer->SetSubImage(imagerect);
}

void SpriteAnimator::_OnInterval()
{
    if(_renderer)
    {
        if(_playing)
        {
            _currentframe++;
            if(_currentframe>_range[1])
            {
                if(_looping){
                    _currentframe=_range[0];
                }
                else
                {
                    _currentframe=_range[1];
                    _playing=false;
                }
            }
        }

        int row=_currentframe/_w;
        int col=_currentframe%_w;
        Rect imagerect(1.0f/_w*col,1.0f/_h*row,1.0f/_w,1.0f/_h);
        _renderer->SetSubImage(imagerect);
    }
}
